var pcConfig = {
    'iceServers': [
       // {url:"stun:stun.xten.com"},
        {urls:"turn:154.221.30.203:3478", username:"test", credential:"test"}
        ]
};
//兼容不同浏览器客户端之间的连接
var PeerConnection = (window.PeerConnection || window.webkitPeerConnection00 || window.webkitRTCPeerConnection || window.mozRTCPeerConnection);

//兼容不同浏览器获取到用户媒体对象
var getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);

//创建数据传输通道配置
var localChannelOptions = {
    ordered: false,
    maxRetransmitTime: 3000,
};

var receiveChannel = null;//远程数据通道
var localChannel = null;//本地数据通道
var pc = null;//客户端之间的连接
var createPcAndDataChannel = function(){
    //创建PeerConnection实例
    pc = new RTCPeerConnection(pcConfig);
    localChannel = pc.createDataChannel('localChannel',localChannelOptions);//本地通道,本地通道接收由远程通道发送过来的数据
    localChannel.onerror = datachannel_error;
    localChannel.onopen = datachannel_open;
    localChannel.onclose = datachannel_close;
    localChannel.onmessage = datachannel_message;
    pc.ondatachannel = pc_datachannel;
    pc.onaddstream = pc_addstream;
    pc.onicecandidate = pc_icecandidate;
}
function getRemoteStream(e){
    // remoteStream = e.streams[0];
    // remoteVideo.srcObject = e.streams[0];
}
//数据通道回调方法
var datachannel_error = function (error) {
    console.log("数据传输通道建立异常:", error);
};
var datachannel_open = function () {
    console.log("本地数据通道建立成功");
};
var datachannel_close = function () {
    console.log("关闭数据传输通道");
};
var datachannel_message = function(event){
    console.log(event.data);
}

//客户端连接回调方法
var downloadFileData = {'maxsize':0,'filename':null,'data':[]};//下载文件数据预存
var pc_datachannel = function(event) {
    receiveChannel = event.channel;//远端的数据通道,注意,这个通道也是可以直接使用的,不过由于它是远端的数据通道,响应的消息会出现在 localChannel.onmessage里面,而不是 receiveChannel.onmessage
    receiveChannel.onmessage = function(event){
        var msg = null
        try{
            msg = JSON.parse(event.data);
        }catch(e){
            if(downloadFileData.filename != null){
                downloadFileData.data.push(event.data);
                var doneSize = 0;
                for(var i = 0 ; i < downloadFileData.data.length ; i++){
                    doneSize += downloadFileData.data[i].byteLength;
                }
                if(downloadFileData.maxsize <= doneSize){//如果已完成长度 <= 最大长度,则代表传输结束
                    var fileBlob = new Blob(downloadFileData.data);
                    var anchor = document.createElement("a");
                    anchor.href = URL.createObjectURL(fileBlob);
                    anchor.download = downloadFileData.filename;
                    anchor.click();
                    downloadFileData = {'maxsize':0,'filename':null,'data':[]};//初始化
                }
            }
            return;
        }
        if(msg.type == 'text'){//接收的是文字传送,当作是聊天文字
            addYouMsg(msg.data,"left");
        }else if(msg != null && msg.type == 'file'){//接收到了对方发来的即将要传送的文件信息
            downloadFileData.maxsize = msg.data.fileSize;
            downloadFileData.filename = msg.data.fileName;
        }
    }
};

var pc_addstream = function(event){//如果检测到媒体流连接到本地，将其绑定到一个video标签上输出
    document.getElementById('remote').src = URL.createObjectURL(event.stream);
};

var pc_icecandidate = function(event){//发送ICE候选到其他客户端
    if (event.candidate !== null) {
        console.log("发送ICE候选到其他客户端==");
        console.log(event.candidate);
        var param = {key:'SIGNALLING_OFFER',value:{
                "event": "_ice_candidate",
                "data": {
                    "candidate": event.candidate
                }
            }};
        socket.sendJson(param);
    }
};

// 发送offer和answer的函数，发送本地session描述
var sendOfferFn = function(desc){
    pc.setLocalDescription(desc);
    console.log("发送offer==");
    console.log(desc);
    var param = {key:'SIGNALLING_OFFER',value:{
            "event": "_offer",
            "data": {
                "sdp": desc
            }
        }};
    socket.sendJson(param);
},sendAnswerFn = function(desc){
    pc.setLocalDescription(desc);
    console.log("发送_answer==");
    console.log(desc);
    var param = {key:'SIGNALLING_OFFER',value:{
            "event": "_answer",
            "data": {
                "sdp": desc
            }
        }};
    socket.sendJson(param);
};
//处理发送过来的信令
var answer = function(value){
    console.log("接收到的信令");
    console.log(value);
    var json = JSON.parse(value);
    //如果是一个ICE的候选，则将其加入到PeerConnection中，否则设定对方的session描述为传递过来的描述
    if(json.event === "_ice_candidate" ){
        pc.addIceCandidate(new RTCIceCandidate(json.data.candidate));
    }else{
        pc.setRemoteDescription( new RTCSessionDescription(json.data.sdp),
            function(){
                // 如果是一个offer，那么需要回复一个answer
                if(json.event === "_offer") {
                    pc.createAnswer(sendAnswerFn, function (error) {
                        console.log("回复信令answer失败:" + error);
                    });
                }
            }
        );
    }
}